import Regex from '@/constants/Regex'
import { CustomerModel } from '@/models/customer'
import { USER } from '@/services/admin/typings'
import { getUserListByRoleKey } from '@/services/admin/user'
import { CustomerChannelVO, getCustomerChannelList } from '@/services/CustomerChannelService'
import { CustomerUpdateDTO, CustomerVO, validateCustomerExist } from '@/services/CustomerService'

import { tenantDrandService, TenantDrandVO } from '@/services/TenantDrandService'
import { useModel } from '@@/exports'
import {
  ModalForm,
  ProFormDateTimePicker,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components'
import { ProFormGroup, ProFormUploadDragger } from '@ant-design/pro-form'
import { ProFormInstance } from '@ant-design/pro-form/lib'
import { RequestOptionsType } from '@ant-design/pro-utils'
import { useRequest } from 'ahooks'
import dayjs from 'dayjs'
import { useRef, useState } from 'react'

export interface CustomerUpdateModalProps {
  onFinish: (formData: any) => Promise<boolean | void>
  customer?: CustomerVO
  open: boolean
  onOpenChange: (state: boolean) => void
}

const CustomerUpdateModal = (props: CustomerUpdateModalProps) => {
  let { getDictList } = useModel('dict')
  let { data: drandList, loading: getDrandListLoading } = useRequest(tenantDrandService.list)
  let {
    data: validatePhoneData,
    run: validatePhoneRun,
    loading: validatePhoneLoading,
  } = useRequest(validateCustomerExist, {
    manual: true,
    debounceWait: 500,
  })

  let {
    data: validateWxIdData,
    run: validateWxIdRun,
    loading: validateWxIdLoading,
  } = useRequest(validateCustomerExist, {
    manual: true,
    debounceWait: 500,
  })

  const formRef = useRef<ProFormInstance>()
  const [inst, setInst] = useState<CustomerUpdateDTO | undefined>()
  const { data: channel, run: flushChannel } = useRequest(getCustomerChannelList)

  const onOpenChange = async (state: boolean) => {
    if (state) {
      let customerVO =
        props.customer ||
        ({
          photoType: '1',
          brandId: drandList?.at(0)?.id,
          createTime: dayjs().format(),
        } as CustomerUpdateDTO)

      let dto: CustomerUpdateDTO = {
        ...props.customer,
        photoType: props.customer?.photoType || '1',
        brandId: props.customer?.brandId || drandList?.at(0)?.id,
        createTime: props.customer?.createTime || dayjs().format('yyyy-MM-dd HH:mm:ss'),
      }
      setInst(dto)
      formRef?.current?.setFieldsValue(customerVO)
    } else {
      setInst(undefined)
      formRef?.current?.resetFields()
    }
    props.onOpenChange(state)
  }

  const onFinish = async (formData: any) => {
    let { channelId } = formData
    let choseChannel = channel?.find((c) => c.id === channelId)
    formData.channelName = choseChannel?.channelName
    return props.onFinish(formData)
  }
  return (
    <>
      <ModalForm
        formRef={formRef}
        title={props.customer ? '修改客资' : '添加客资'}
        open={props.open}
        initialValues={inst}
        onFinish={onFinish}
        onOpenChange={onOpenChange}
      >
        <ProFormGroup>
          <ProFormText label="客户id" hidden name="id" />
          <ProFormText label="客户名" name="name" rules={[{ required: true, message: '请填写客户姓名' }]} />
          <ProFormText
            label="微信号"
            name="wxId"
            validateStatus={
              validateWxIdLoading ? '' : validateWxIdData && validateWxIdData.length > 0 ? 'warning' : 'success'
            }
            help={validateWxIdData && validateWxIdData.length > 0 && '微信号已存在'}
            fieldProps={{
              onChange: (e) => {
                let wxId = e.target.value
                validateWxIdRun({ wxId })
              },
            }}
          />
          <ProFormText
            label="手机号"
            name="phone"
            allowClear={false}
            rules={[{ pattern: Regex.PHONE, message: '请输入正确的手机号' }]}
            validateStatus={
              validatePhoneLoading ? '' : validatePhoneData && validatePhoneData.length > 0 ? 'warning' : 'success'
            }
            help={validatePhoneData && validatePhoneData.length > 0 && '手机号已存在'}
            fieldProps={{
              onChange: (e) => {
                let phone = e.target.value
                if (phone.length < 11) {
                  return
                }
                validatePhoneRun({ phone })
              },
            }}
          />

          <ProFormSelect<TenantDrandVO[]>
            label="品牌"
            name="brandId"
            rules={[{ required: true, message: '请选择品牌' }]}
            options={drandList}
            fieldProps={{
              defaultActiveFirstOption: true,
              fieldNames: { label: 'brandName', value: 'id' },
            }}
          />

          <ProFormSelect
            label="拍摄类型"
            name="photoType"
            rules={[{ required: true, message: '请选择拍摄类型' }]}
            request={async () => getDictList('photo_type') as RequestOptionsType[]}
          />

          <ProFormSelect
            width="md"
            label="渠道"
            name="channelId"
            rules={[{ required: true, message: '请选择渠道' }]}
            request={async () => {
              await flushChannel()
              return channel?.map((c: CustomerChannelVO) => ({
                label: c.channelName,
                value: c.id,
              })) as RequestOptionsType[]
            }}
          />
          <ProFormSelect
            label="销售"
            name="sellerUserId"
            rules={[{ required: true, message: '请选择销售人员' }]}
            request={async () => {
              let userList = await getUserListByRoleKey('seller')
              return userList?.map((user: USER.UserVO) => ({
                label: user.userName,
                value: user.id,
              })) as RequestOptionsType[]
            }}
          />
          <ProFormSelect
            label="跟进状态"
            name="followUpStateId"
            request={async () => getDictList('follow_up_type') as RequestOptionsType[]}
          />
          <ProFormDateTimePicker
            label="创建时间"
            name="createTime"
            rules={[{ required: true, message: '请选择创建时间' }]}
            transform={(value) => ({ createTime: dayjs(value).format('YYYY-MM-DD HH:mm:ss') })}
          />
        </ProFormGroup>

        <ProFormUploadDragger
          name="attachUrl"
          label="上传图片"
          accept="image/*"
          description=" "
          convertValue={(v) => {
            if (typeof v === 'string') {
              return []
            }
            return v
          }}
          fieldProps={{
            name: 'file',
            onChange: (info) => {
              if (info.file.status === 'done') {
                CustomerModel.state.uploadUrl = info.file.response.data[0].url
              }
            },
          }}
          max={1}
          action="/api/file/upload"
        />
        <ProFormTextArea label="备注" name="remark" />
      </ModalForm>
    </>
  )
}

export default CustomerUpdateModal
